package com.zyfdroid.ambernicstartmenu.service;

import android.accessibilityservice.AccessibilityService;
import android.content.Context;
import android.util.Log;
import android.view.KeyEvent;
import android.view.accessibility.AccessibilityEvent;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.function.Function;
import android.os.Handler;

public class KeyInjectorService extends AccessibilityService {


    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {

    }

    @Override
    public void onInterrupt() {

    }

    private long lastTrigger = -1;

    final String TAG="KeyInjectorService";
    private long f10DownTime = 0;

    private Runnable f10Delay = new Runnable() {
        @Override
        public void run() {
            performGlobalAction(GLOBAL_ACTION_RECENTS);
        }
    };

    @Override
    protected boolean onKeyEvent(KeyEvent event) {
        Log.w(TAG, "onKeyEvent: "+event.getKeyCode()+", "+event.getAction()+", "+temporyDisableInjection);
        if(event.getAction()== KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_F10){
            if(temporyDisableInjection){
                temporyDisableInjection = false;
                return super.onKeyEvent(event);
            }
            f10DownTime = System.currentTimeMillis();
            if(System.currentTimeMillis() - lastTrigger > 680){
                invokeAssistButton();
                lastTrigger = System.currentTimeMillis();
            }
            handler.postDelayed(f10Delay,800);
            return true;
        }
        if(event.getAction()== KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_F10){
            try {
                handler.removeCallbacks(f10Delay);
            }catch (Exception ex){

            }
        }
        return super.onKeyEvent(event);
    }

    private void invokeAssistButton(){
        doInputKeyCode("KEYCODE_ASSIST");
    }

    public void doInputKeyCode(String keycode){
        try {
            Runtime.getRuntime().exec("su -0 input keyevent "+keycode);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void setAirplaneMode(boolean mode){
        try {
            Process ps = Runtime.getRuntime().exec("su");
            OutputStream stdin = ps.getOutputStream();
            stdin.write(("settings put global airplane_mode_on "+(mode ? "1" : "0")+"\n\n" +
                    "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state "+(mode ? "true" : "false")+"\n\nexit\n").getBytes(StandardCharsets.UTF_8));
            stdin.flush();
            stdin.close();
            ps.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static KeyInjectorService mInstance = null;
    Handler handler;
    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        handler = new Handler();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mInstance = null;
    }

    public static KeyInjectorService getInstance(){
        return mInstance;
    }

    public void showQuickSettings(){
        performGlobalAction(GLOBAL_ACTION_QUICK_SETTINGS);
    }

    boolean temporyDisableInjection = false;
    public void doSwitchRG(){
        // 通过Root权限模拟的输入事件，似乎不会被无障碍拦截
        // temporyDisableInjection = true;
        doInputKeyCode("KEYCODE_F10");
    }

    @FunctionalInterface
    public interface DoWithKeyInjectorServiceAction{
        void doAction(KeyInjectorService service);
    }

    public static void runWithService(Context ctx, DoWithKeyInjectorServiceAction action){
        if (mInstance == null) {
            Toast.makeText(ctx, "无障碍服务未运行", Toast.LENGTH_SHORT).show();
            return;
        }
        action.doAction(mInstance);
    }
}
